//
//  ImageBrowerVC.swift
//  WBSwift
//
//  Created by maker on 2016/11/24.
//  Copyright © 2016年 maker. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

let picCell = "picCell"

class ImageBrowerVC: UIViewController {
    var index : IndexPath?{
        didSet{

        }
    }
    var imageUrls :[URL]?
    var bigUrls :[String] = [String]()
    
    lazy var collectionView : UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: picCollectionLayout())
    lazy var saveBtn : UIButton = UIButton(font: 14, bgColor: UIColor.gray, title: "退  出")
    lazy var shareBtn : UIButton = UIButton(font: 14, bgColor: UIColor.gray, title: "保  存")
    
    init(index:IndexPath,imageUrls:[URL]) {
        super.init(nibName: nil, bundle: nil)
        self.imageUrls = imageUrls
        self.index = index
        saveBigUrl(imageUrls)
       
    }
    override func loadView() {
        super.loadView()
        view.frame.size.width += 20
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        //开启一个线程监听 collectionView 的 Window 是否有值
        DispatchQueue.global().async {
            while true {
                if self.collectionView.window != nil{
                    break
                }
            }
            
            DispatchQueue.main.async(execute: {
               self.collectionView.scrollToItem(at: self.index!, at: .left, animated: false)
               
            })
        }
        
    }
}

//MARK:==========设置 UI==========
extension ImageBrowerVC{
    func setupUI() {
        view.addSubview(collectionView)
        view.addSubview(saveBtn)
        view.addSubview(shareBtn)
        
        //布局
        collectionView.snp_makeConstraints { (make) in
            
            make.left.equalTo(0)
            make.width.equalTo(self.view.widths())
            make.top.equalTo(0)
            make.height.equalToSuperview()
        }
        saveBtn.snp_makeConstraints { (make) in
            make.left.equalTo(20)
            make.bottom.equalTo(-20)
            make.width.equalTo(90)
            make.height.equalTo(32)
        }
        shareBtn.snp_makeConstraints { (make) in
            make.right.equalTo(-40)
            make.top.equalTo(saveBtn)
            make.width.equalTo(saveBtn)
            make.height.equalTo(saveBtn)
        }
        
        //设置属性
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(BrowerCollectionCell.self, forCellWithReuseIdentifier: picCell)

        
        shareBtn.addTarget(self, action: #selector(ImageBrowerVC.shareClick), for: .touchUpInside)
        saveBtn.addTarget(self, action: #selector(ImageBrowerVC.saveClick), for: .touchUpInside)
    }
}

//MARK:==========点击事件==========
extension ImageBrowerVC{
    @objc fileprivate func shareClick() {
        let imageCell = collectionView.visibleCells.first as! BrowerCollectionCell
        guard let saveImage = imageCell.iv.image else{
            return
        }
        
        //把图片保存到相册
        UIImageWriteToSavedPhotosAlbum(saveImage, self, #selector(ImageBrowerVC.image(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    @objc fileprivate func saveClick() {
        dismiss(animated: true, completion: nil)
    }
    
    /*
     图片保存的回调
     - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
     1.(void *)是 AnyObject 类型
     2.外部参数didFinishSavingWithError 系统回调的参数error 函数的内部可以使用的标识符
     */
    func image(_ image:UIImage,didFinishSavingWithError error :NSError?,contextInfo:AnyObject) {
        
        var errorInfo = ""
        
        if error != nil {
            errorInfo = "保存出错了~"
        }else{
            errorInfo = "保存成功"
        }
        SVProgressHUD.showInfo(withStatus: errorInfo)
    }
}

//MARK:========== collection 代理==========
extension ImageBrowerVC:UICollectionViewDelegate,UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        guard let count = imageUrls?.count else {
            return 1
        }
        return count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: picCell, for: indexPath) as! BrowerCollectionCell
        
        cell.url = imageUrls![indexPath.item]
        cell.delegate = self
        
        return cell
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    }
}

//MARK:==========cell 的自定义代理==========
extension ImageBrowerVC : PhotoBrowerCellDelegate{
    func imageClick() {
        saveClick()
    }
}

//MARK:==========把大图片存成 plist==========
extension ImageBrowerVC{
    func saveBigUrl(_ urls : [URL]?) {
        guard let imageUrls = imageUrls else {
            return
        }
        for smallUrl in imageUrls {
            let smallString = smallUrl.absoluteString
            let bigString = smallString.replacingOccurrences(of: "thumbnail", with: "bmiddle")
            bigUrls.append(bigString)
        }
   
    }
}

//MARK:==========动画的代理==========
extension ImageBrowerVC : dismissAnimatorDelegate{
    func getImageview() -> UIImageView {
        //1.获取当前显示的 cell
        let cell = self.collectionView.visibleCells.first as! BrowerCollectionCell
        
        let iv = UIImageView()
        iv.image = cell.iv.image
        iv.frame = cell.iv.frame
        
        iv.contentMode = .scaleAspectFill
        iv.clipsToBounds = true
        
        return iv
    }
    
    func getIndexpath() -> IndexPath {
         let cell = self.collectionView.visibleCells.first as! BrowerCollectionCell
        return collectionView.indexPath(for: cell)!
    }
}

//MARK:==========布局类==========
class picCollectionLayout: UICollectionViewFlowLayout {
    override func prepare() {
        itemSize = CGSize(width: (collectionView?.widths())!, height: screenHeight)
        minimumLineSpacing = 0.0
        minimumInteritemSpacing = 0.0
        scrollDirection = .horizontal
        
        self.collectionView?.showsVerticalScrollIndicator = false
        self.collectionView?.showsHorizontalScrollIndicator = false
        self.collectionView?.isPagingEnabled = true
    }
}





